﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlexPlatform.Shared.Configuration;
using Microsoft.Practices.Unity;

namespace FlexPlatform.Common.Configuration
{
    using System.Collections.ObjectModel;

    public class ConfigurationContainer
    {
        private Dictionary<Type, List<IConfigurationElement>> clsConfigurationDictionary;

        public ConfigurationContainer()
        {
            clsConfigurationDictionary = new Dictionary<Type, List<IConfigurationElement>>();
        }

        public IEnumerable<IConfigurationElementType> GetConfigurationElementsOfType<IConfigurationElementType>(Type entityType) where IConfigurationElementType : IConfigurationElement
        {
            return (clsConfigurationDictionary[entityType].OfType<IConfigurationElementType>());
        }

        public IEnumerable<IConfigurationElement> GetConfigurationElements<IConfigurationElementType>(Type entityType) where IConfigurationElementType : IConfigurationElement
        {
            return (IEnumerable<IConfigurationElement>)(clsConfigurationDictionary[entityType].Where(x => x.GetType().IsAssignableFrom(typeof(IConfigurationElement))));
        }

        public IEnumerable<IConfigurationElement> GetAllConfigurationElements(Type entityType)
        {
            if (clsConfigurationDictionary.Keys.Contains(entityType))
            {
                return (clsConfigurationDictionary[entityType]);
            }
            else
            {
                return new Collection<IConfigurationElement>();
            }
           
        }

        public void RegisterConfigurationElement<EntityType>(IConfigurationElement configurationObject) 
        {
            // create the entry for the EntityType if does not exist:
            Type entityType = typeof(EntityType);
            List<IConfigurationElement> entityConfigurationElements;

            if (!clsConfigurationDictionary.ContainsKey(entityType))
            {
                entityConfigurationElements = new List<IConfigurationElement>();
                clsConfigurationDictionary.Add(entityType, entityConfigurationElements);
            }
            else
            {
                entityConfigurationElements = clsConfigurationDictionary[entityType];
            }

            // now add the configuration element
            // if an element with the same name exists, throw an exception
            if (entityConfigurationElements.Contains(configurationObject))
            {
                entityConfigurationElements.Add(configurationObject);
            }
            else
            {
                throw new InvalidOperationException(string.Format("The same configuration element already exists for this entity type! [entity type = {0} ]", entityType));
            }            
        }


    }
}
